import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/providers/gallery_provider.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/localstorage.dart';
import 'package:geomancy/widgets/gallery_util/components/index.dart';
import 'package:geomancy/widgets/modal_util/index.dart';
import 'package:geomancy/widgets/permission_reson_modal.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

class TabClassicType {
  AssetPathEntity path;
  int count;
  AssetEntity entity;

  TabClassicType({required this.path, required this.count, required this.entity});
}

class GalleryUtils {
  static const pageCount = 80;
  ///存储相册图集列表
  static List<TabClassicType> _galleryTypeList = [];

  static set setGalleryTypeList(List<TabClassicType> value) {
    _galleryTypeList = value;
  }

  static get getGalleryTypeList => _galleryTypeList;

  ///获取相机权限
  static Future getCameraPermission({required BuildContext context, required Function success, Function? failed}) async {
    var status = await Permission.camera.status;
    if (status == PermissionStatus.granted) {
      success();
    } else {
      LocalStorage prefs = await LocalStorage.getInstance();
      final showPermissionDialog = prefs.getBoolean(Constant.SHOWCAMERAPERMISSIONDIALOG);
      if (showPermissionDialog != false && Platform.isAndroid) {
        // ignore: use_build_context_synchronously
        PermissionReasonModal.show(context, Constant.CAMERAPERMISSIONTIPS);
      }
      prefs.setBoolean(Constant.SHOWCAMERAPERMISSIONDIALOG, false);
      status = await Permission.camera.request();
      PermissionReasonModal.cancel();
      if (status == PermissionStatus.granted) {
        success();
      } else {
        if (failed != null) {
          failed();
        }
      }
    }
  }

  ///获取相册权限
  static Future getPermission({required BuildContext context, required Function success, Function? failed}) async {
    bool requestPhoto = true;
    if (Platform.isAndroid) {
      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      final androidRelease = int.parse(androidInfo.version.release);
      if (androidRelease < 13) {
        requestPhoto = false;
      }
    }
    var status = requestPhoto ? await Permission.photos.status : await Permission.storage.status;
    if (status == PermissionStatus.granted) {
      success();
    } else {
      LocalStorage prefs = await LocalStorage.getInstance();
      final showPermissionDialog = prefs.getBoolean(Constant.SHOWPHOTOPERMISSIONDIALOG);
      if (showPermissionDialog != false && Platform.isAndroid) {
        // ignore: use_build_context_synchronously
        PermissionReasonModal.show(context, Constant.PHOTOPERMISSIONTIPS, height: 280.w);
      }
      prefs.setBoolean(Constant.SHOWPHOTOPERMISSIONDIALOG, false);

      final PermissionState ps = await PhotoManager.requestPermissionExtend();
      PermissionReasonModal.cancel();

      if (ps.hasAccess) {
        // 已获取到权限。
        success();
      } else {
        if (failed != null) {
          failed();
        }
      }
    }
  }

  ///注册资源变动的通知回调
  static addListener(void Function(MethodCall) callback) {
    PhotoManager.addChangeCallback(callback);
    PhotoManager.startChangeNotify();
  }
  ///移除资源变动的通知回调
  static removeListener(void Function(MethodCall) callback) {
    PhotoManager.stopChangeNotify();
    PhotoManager.removeChangeCallback(callback);
  }

  ///打开相册
  static openGallery(BuildContext context, {
    GalleryScene scene = GalleryScene.common,
    RequestType type = RequestType.common,
    int maxCount = 9,
    Color barrierColor = Colors.transparent,
    Function? callback
  }) async {
    await ModalUtil.showBottomModal(
      context: context,
      barrierColor: barrierColor,
      backgroundColor: Colors.transparent,
      radius: 60.w,
      child: (state) {
        return GalleryWidget(
          scene: scene,
          requestType: type,
          maxCount: maxCount,
        );
      },
    );
    if (callback != null) {
      callback();
    }
  }

  ///获取相册分类信息
  static Future<List<AssetPathEntity>> getGalleryType({RequestType type = RequestType.common}) async {
    return await PhotoManager.getAssetPathList(type: type);
  }

  /// 根据参数获取相册图片 AssetEntity，并使用 Stream 持续输出每一页数据
  static Stream<List<AssetEntity>> getAssetEntityListByType(BuildContext context, RequestType type) async* {
    /// 提前保存GalleryProvider实例的引用
    final galleryProvider = context.read<GalleryProvider>();
    final int count = await PhotoManager.getAssetCount(); // 获取总图片数
    final int totalPage = (count / pageCount).ceil(); // 计算总页数
    List<AssetEntity> tmpList = [];
    for (int page = 0; page < totalPage; page++) {
      // 获取当前页的 AssetEntity 列表
      final List<AssetEntity> entities = await PhotoManager.getAssetListPaged(page: page, pageCount: pageCount, type: type);
      tmpList.addAll(entities);
      galleryProvider.setAllGalleryMediaList = tmpList;
      // 每页加载完成后通过 Stream 向外部发送数据
      yield entities;
    }
  }
}